import os
import sys
import time

import easyocr
import mss
import numpy as np
import pyautogui
import pyperclip
from PIL import Image
import pytesseract
from uiautomation import uiautomation

from Config import root_path


def mouse_move_to(x, y, time=0.3):
    """
    将鼠标移动到指定坐标位置
    :param x: 横坐标
    :param y: 纵坐标
    :param time: 移动的时长，默认0.3秒
    :return:
    """
    pyautogui.moveTo(x, y, time)


def mouse_move_to_and_click(x, y, time=0.3, button=pyautogui.LEFT):
    """
    将鼠标移动到指定坐标位置
    :param x: 横坐标
    :param y: 纵坐标
    :param time: 移动的时长，默认0.3秒
    :param button: 鼠标按键
    :return:
    """
    if os.path.exists("{}/stop.txt".format(root_path)):
        sys.exit()
    pyautogui.moveTo(x, y, time)
    pyautogui.click(button=button)


def click(button=pyautogui.LEFT):
    """
    点击鼠标左键
    :return:
    """
    pyautogui.click(button=button)


def double_click(button=pyautogui.LEFT):
    """
    鼠标双击
    :return:
    """
    pyautogui.doubleClick(button=button)


def get_control_by_level(level, base_id=None, base_name=None, base_depth=1):
    """
    根据层级获取到控件
    :param level: 层级数组
    :param base_id: 基准窗口id
    :param base_name: 控件名称
    :param base_depth: 控件深度
    :return:
    """
    if base_id:
        control = uiautomation.WindowControl(AutomationId=base_id)
    elif base_name:
        control = uiautomation.WindowControl(SubName=base_name, searchDepth=base_depth)
    else:
        raise Exception("请输入正确的参数")
    for index in level:
        control = control.GetChildren()[index]
    return control


def get_control_position(control):
    """
    获取控件的坐标位置
    :param control: 控件
    :return:
    """
    rect = control.BoundingRectangle
    return rect.left, rect.top, rect.width(), rect.height()


def get_current_position_rgb():
    """
    获取当前鼠标的RGB值
    :return:
    """
    x, y = pyautogui.position()
    rgb = pyautogui.screenshot().getpixel((x, y))
    return rgb


def get_position_rgb(x, y):
    """
    获取指定坐标的RGB值
    :param x: X轴坐标值
    :param y: Y轴坐标值
    :return:
    """
    rgb = pyautogui.screenshot().getpixel((x, y))
    return rgb


def clear_and_send_keys(content, check=True, check_function=None):
    """
    清理并输入数据
    :param content:
    :return:
    """
    pyautogui.hotkey('ctrl', 'a')
    for _ in str(content):
        pyautogui.typewrite(_)
        time.sleep(0.1)
    if check:
        pyautogui.hotkey("ctrl", "a")
        time.sleep(0.1)
        pyautogui.hotkey("ctrl", "c")
        paste = pyperclip.paste()
        if str(content).strip() != str(paste).strip():
            time.sleep(1)
            clear_and_send_keys(content, check=check, check_function=check_function)
    if check_function is not None:
        check_result = check_function(content)
        if not check_result:
            clear_and_send_keys(content, check=check, check_function=check_function)


def center_position(img, confidence=0.9):
    """
    获取已存在图片的中心点坐标
    :param img: 要寻找的图片
    :param confidence: 图片的相似度
    :return:
    """
    _position = pyautogui.locateOnScreen(img, confidence=confidence)
    return _position[0] + _position[2] / 2, _position[1] + _position[3] / 2


def change_cwd(before_cwd, after_cwd):
    """
    切换工作目录装饰器，会在调用方法的时候将工作目录切换到after_cwd，方法调用完成会切换回来
    :param before_cwd: 当前的工作目录
    :param after_cwd: 需要切换到的工作目录
    :return:
    """

    def wrapper1(func):
        def wrapper(*args, **kwargs):
            is_different = True
            if before_cwd == after_cwd:
                is_different = False
            if is_different:
                os.chdir(after_cwd)
            try:
                result = func(*args, **kwargs)
            finally:
                if is_different:
                    os.chdir(before_cwd)
            return result

        return wrapper

    return wrapper1


def get_text_from_region(left, top, width, height):
    """
    获取指定区域的文本
    :param left:
    :param top:
    :param width:
    :param height:
    :return:
    """
    # 初始化 EasyOCR 读取器
    reader = easyocr.Reader(['ch_sim', 'en'])

    # 定义屏幕区域
    monitor = {'top': top, 'left': left, 'width': width, 'height': height}  # 替换为你需要的区域

    # 使用 mss 截取屏幕
    with mss.mss() as sct:
        screenshot = sct.grab(monitor)
        screenshot_np = np.array(screenshot)

    # 使用 EasyOCR 提取文字
    results = reader.readtext(screenshot_np)

    # 输出提取的文字
    for detection in results:
        text = detection[1]

    return text


if __name__ == "__main__":
    pass
